"use client"

import { useState } from "react"
import { View, Text, StyleSheet, TouchableOpacity, TextInput, ScrollView, Platform, Alert } from "react-native"
import { SafeAreaView } from "react-native-safe-area-context"
import { ArrowLeft, Bookmark, Edit2, Trash2 } from "lucide-react-native"
import { useRouter, useLocalSearchParams } from "expo-router"
import { theme } from "../constants/theme"
import { AddUnitModal } from "../components/favorites/AddUnitModal"
import { EditUnitModal } from "../components/favorites/EditUnitModal"

// 模拟单元数据
interface Unit {
    id: string
    name: string
    wordCount: number
}

interface Collection {
    id: string
    title: string
    units: Unit[]
}

export default function CollectionEditScreen() {
    const router = useRouter()
    const params = useLocalSearchParams()
    const collectionId = params.id as string

    // 状态管理
    const [collection, setCollection] = useState<Collection>({
        id: collectionId,
        title: (params.title as string) || "",
        units: [
            { id: "1", name: "watch", wordCount: 0 },
            { id: "2", name: "Unit 2", wordCount: 12 },
        ],
    })
    const [addUnitModalVisible, setAddUnitModalVisible] = useState(false)
    const [editUnitModalVisible, setEditUnitModalVisible] = useState(false)
    const [selectedUnit, setSelectedUnit] = useState<Unit | null>(null)

    // 处理返回
    const handleBack = () => {
        router.back()
    }

    // 处理添加单元
    const handleAddUnit = (name: string) => {
        const newUnit = {
            id: `unit-${Date.now()}`,
            name,
            wordCount: 0,
        }
        setCollection((prev) => ({
            ...prev,
            units: [...prev.units, newUnit],
        }))
        setAddUnitModalVisible(false)
    }

    // 处理编辑单元
    const handleEditUnit = (unitId: string, newName: string) => {
        setCollection((prev) => ({
            ...prev,
            units: prev.units.map((unit) => (unit.id === unitId ? { ...unit, name: newName } : unit)),
        }))
        setEditUnitModalVisible(false)
        setSelectedUnit(null)
    }

    // 处理删除单元
    const handleDeleteUnit = (unitId: string) => {
        Alert.alert("删除单元", "确定要删除这个单元吗？此操作不可恢复。", [
            { text: "取消", style: "cancel" },
            {
                text: "删除",
                style: "destructive",
                onPress: () => {
                    setCollection((prev) => ({
                        ...prev,
                        units: prev.units.filter((unit) => unit.id !== unitId),
                    }))
                },
            },
        ])
    }

    // 处理保存
    const handleSave = () => {
        if (!collection.title.trim()) {
            Alert.alert("提示", "请输入单词本名称")
            return
        }

        // 这里添加保存逻辑
        console.log("保存收藏本:", collection)
        Alert.alert("成功", "保存成功", [{ text: "确定", onPress: () => router.back() }])
    }

    return (
        <SafeAreaView style={styles.container} edges={["top"]}>
            {/* 头部 */}
            <View style={styles.header}>
                <TouchableOpacity onPress={handleBack} style={styles.backButton}>
                    <ArrowLeft size={24} color={theme.colors.neutral.black} />
                </TouchableOpacity>
                <Text style={styles.headerTitle}>编辑收藏本</Text>
                <View style={{ width: 40 }} />
            </View>

            <ScrollView style={styles.content} contentContainerStyle={styles.contentContainer}>
                {/* 单词本名称 */}
                <Text style={styles.sectionTitle}>单词本名称</Text>
                <TextInput
                    style={styles.nameInput}
                    value={collection.title}
                    onChangeText={(text) => setCollection((prev) => ({ ...prev, title: text }))}
                    placeholder="请输入单词本名称"
                    placeholderTextColor={theme.colors.neutral.gray}
                />

                {/* 单元列表 */}
                <View style={styles.unitsHeader}>
                    <Text style={styles.sectionTitle}>单元名称</Text>
                    <TouchableOpacity onPress={() => setAddUnitModalVisible(true)}>
                        <Text style={styles.addUnitText}>新建单元</Text>
                    </TouchableOpacity>
                </View>

                <View style={styles.unitsList}>
                    {collection.units.map((unit) => (
                        <View key={unit.id} style={styles.unitItem}>
                            <View style={styles.unitLeft}>
                                <Bookmark size={20} color={theme.colors.primary.default} />
                                <Text style={styles.unitName}>{unit.name}</Text>
                            </View>
                            <View style={styles.unitActions}>
                                <TouchableOpacity
                                    style={styles.unitAction}
                                    onPress={() => {
                                        setSelectedUnit(unit)
                                        setEditUnitModalVisible(true)
                                    }}
                                >
                                    <Edit2 size={18} color={theme.colors.neutral.gray} />
                                </TouchableOpacity>
                                <TouchableOpacity style={styles.unitAction} onPress={() => handleDeleteUnit(unit.id)}>
                                    <Trash2 size={18} color={theme.colors.neutral.gray} />
                                </TouchableOpacity>
                            </View>
                        </View>
                    ))}
                </View>
            </ScrollView>

            {/* 保存按钮 */}
            <View style={styles.footer}>
                <TouchableOpacity style={styles.saveButton} onPress={handleSave}>
                    <Text style={styles.saveButtonText}>保存</Text>
                </TouchableOpacity>
            </View>

            {/* 添加单元模态框 */}
            <AddUnitModal
                visible={addUnitModalVisible}
                onClose={() => setAddUnitModalVisible(false)}
                onConfirm={handleAddUnit}
            />

            {/* 编辑单元模态框 */}
            <EditUnitModal
                visible={editUnitModalVisible}
                unit={selectedUnit}
                onClose={() => {
                    setEditUnitModalVisible(false)
                    setSelectedUnit(null)
                }}
                onConfirm={handleEditUnit}
            />
        </SafeAreaView>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: theme.colors.neutral.white,
    },
    header: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        paddingHorizontal: theme.spacing.lg,
        paddingVertical: theme.spacing.md,
        borderBottomWidth: 1,
        borderBottomColor: theme.colors.neutral.lightGray,
    },
    backButton: {
        width: 40,
        height: 40,
        borderRadius: 20,
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: theme.colors.neutral.lightGray,
    },
    headerTitle: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
    },
    content: {
        flex: 1,
    },
    contentContainer: {
        padding: theme.spacing.lg,
    },
    sectionTitle: {
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.medium,
        color: theme.colors.neutral.black,
        marginBottom: theme.spacing.md,
    },
    nameInput: {
        backgroundColor: theme.colors.neutral.lightGray,
        borderRadius: theme.borderRadius.extraLarge,
        paddingHorizontal: theme.spacing.lg,
        paddingVertical: theme.spacing.md,
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.black,
        marginBottom: theme.spacing.xl,
    },
    unitsHeader: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        marginBottom: theme.spacing.md,
    },
    addUnitText: {
        fontSize: theme.fontSize.md,
        color: theme.colors.primary.default,
        fontWeight: theme.fontWeight.medium,
    },
    unitsList: {
        gap: theme.spacing.md,
    },
    unitItem: {
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        backgroundColor: theme.colors.neutral.lightGray,
        borderRadius: theme.borderRadius.extraLarge,
        paddingVertical: theme.spacing.md,
        paddingHorizontal: theme.spacing.lg,
    },
    unitLeft: {
        flexDirection: "row",
        alignItems: "center",
        gap: theme.spacing.md,
    },
    unitName: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.black,
    },
    unitActions: {
        flexDirection: "row",
        gap: theme.spacing.md,
    },
    unitAction: {
        padding: theme.spacing.xs,
    },
    footer: {
        padding: theme.spacing.lg,
        paddingBottom: Platform.OS === "ios" ? 34 : theme.spacing.lg,
        borderTopWidth: 1,
        borderTopColor: theme.colors.neutral.lightGray,
    },
    saveButton: {
        backgroundColor: theme.colors.primary.default,
        borderRadius: theme.borderRadius.extraLarge,
        paddingVertical: theme.spacing.lg,
        alignItems: "center",
    },
    saveButtonText: {
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.white,
    },
})

